package com.hh.generator.core.generator;

import com.hh.generator.common.dto.ColumnEntity;
import com.hh.generator.common.dto.TableEntity;
import com.hh.generator.core.Generator;
import com.hh.generator.core.model.*;

import java.util.List;
import java.util.stream.Collectors;

import static com.hh.generator.common.util.TableToClassConvertUtil.*;

public class MapperXmlGenerator extends AbstractTableBaseGenerator implements Generator {

    private String templateName = "Mapper.xml.vm";

    public MapperXmlGenerator(Config config, TableEntity tableEntity, List<ColumnEntity> columnEntityList) {
        super(config, tableEntity, columnEntityList);
    }

    @Override
    public String fileName() {
        return mapperClassName(config.getTablePrefix(), tableEntity.getTableName()) + ".xml";
    }

    @Override
    public ClassModel buildModel() {
        String entityClassName = className(config.getTablePrefix(), tableEntity.getTableName());
        String infoClassName = infoClassName(config.getTablePrefix(), tableEntity.getTableName());
        String infoClassFullName = config.getInfoPackage().replace("xx", config.getModule()) + "." + infoClassName;
        List<FieldModel> fieldModels = buildFieldModels();
        fieldModels = fieldModels.stream().filter(fieldModel -> !config.getEntityDefaultFields().contains(fieldModel.getFieldName())).collect(Collectors.toList());

        MapperXmlModel model = new MapperXmlModel();
        model.setTableName(tableEntity.getTableName());
        model.setInfoClassFullName(infoClassFullName);
        if (config.getMethods().contains("query")) {
            FacadeModel.Method method = new FacadeModel.Method();
            method.setMethodName("query" + entityClassName);
            model.setQueryMethod(method);
        }
        if (config.getMethods().contains("get")) {
            FacadeModel.Method method = new FacadeModel.Method();
            method.setMethodName("get" + entityClassName + "ById");
            model.setGetMethod(method);
        }
        if (config.getMethods().contains("list")) {
            FacadeModel.Method method = new FacadeModel.Method();
            method.setMethodName("list" + entityClassName);
            model.setListMethod(method);
        }
        model.setPackageName(config.getMapperPackage().replace("xx", config.getModule()));
        model.setComment(tableEntity.getTableComment() + " Mapper接口");
        model.setAuthor(config.getClassAuthor());
        model.setDate(config.getDate());
        model.setClassName(mapperClassName(config.getTablePrefix(), tableEntity.getTableName()));
        model.setClassFullName(model.getPackageName() + "." + model.getClassName());
        model.setFields(fieldModels);
        return model;
    }

    @Override
    public String getTemplateName() {
        return templateName;
    }

}
